package com.lishe.lishe.lishe.module.mall.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.google.gson.Gson;
import com.lishe.base.common.adapter.CommonAdapter;
import com.lishe.base.common.adapter.MultiItemTypeAdapter;
import com.lishe.base.common.adapter.base.ViewHolder;
import com.lishe.base.common.adapter.wrapper.HeaderAndFooterWrapper;
import com.lishe.base.common.base.AbstractFragment;
import com.lishe.base.mvp.factory.CreatePresenter;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerGriadViewItemDecoration;
import com.lishe.lishe.lishe.module.mall.adapter.BannerItemViewDelegate;
import com.lishe.lishe.lishe.module.mall.adapter.CategoryItemViewDelegate;
import com.lishe.lishe.lishe.module.mall.adapter.GoodsItemViewDelegate;
import com.lishe.lishe.lishe.module.mall.adapter.MainMenuItemViewDelegate;
import com.lishe.lishe.lishe.module.mall.adapter.TitleItemViewDelegate;
import com.lishe.lishe.lishe.module.mall.bean.DataItemBean;
import com.lishe.lishe.lishe.module.mall.bean.GoodsItemsBean;
import com.lishe.lishe.lishe.module.mall.bean.GoodsMallResponse;
import com.lishe.lishe.lishe.module.mall.bean.HomeResponse;
import com.lishe.lishe.lishe.module.mall.presenter.IndexPresenter;
import com.lishe.lishe.lishe.module.mall.presenter.IndexView;
import com.lishe.lishe.lishe.module.search.activity.HomeSearchActivity;
import com.lishe.lishe.lishe.utils.FullyLinearLayoutManager;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 标    题：首页
 * 功能描述：homefragment.MallRecyClerViewAdapter;MallObject;MallTitleActivityAdapter;MallClassifyAdapter;MallValuseAdapter
 * MallSelectActivityAdapter;MallMaybeLikeAdapter;MallSelectActivityItemAdapter
 * MallGoods；MallItemObject这些都可以删掉
 * 作    者：zouxx
 * 创建时间：2018/8/13
 */
@CreatePresenter(IndexPresenter.class)
public class IndexFragment extends AbstractFragment<IndexView, IndexPresenter> implements IndexView {

    private View rootView;// cache fragment view
    private LinearLayout search;
    private SmartRefreshLayout refreshlayout;
    private RecyclerView recyclerView;
    private LinearLayout errorLayout;
    private TextView errorRetry;
    private View top;

    private List<GoodsItemsBean> goodsLists = new ArrayList<>();
    private List<DataItemBean> headLists = new ArrayList<>();

    private int page = 1;
    private int mCurrentY = 0;
    private int totalPage = 1;
    private HeaderAndFooterWrapper wrapper;
    private boolean hasAddHeadTitle = false;
    private View titleView;
    private TextView title;
    private ImageView icon;
    private MultiItemTypeAdapter headAdapter;

    private volatile static IndexFragment singleton = null;

    public static IndexFragment getInstance()   {
        if (singleton == null)  {
            synchronized (IndexFragment.class) {
                if (singleton == null)  {
                    singleton= new IndexFragment();
                }
            }
        }
        return singleton;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home, null);
            initView(rootView);
            LoadingUtils.createDefaultDialog(getActivity());
            getMvpPresenter().getIndexHeadData();
            //取出保存的data展示
            String data = SharedPreferencesUtils.getHomeData();
            if (data != null && !"".equals(data)) {
                try {
                    HomeResponse response = new Gson().fromJson(data, HomeResponse.class);
                    headLists.addAll(response.data);
                    headAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return rootView;
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (getView() != null) {
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void requestFailure(int errorCode, String msg) {
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadmore();
        if (headLists.size() == 0) {
            errorLayout.setVisibility(View.VISIBLE);
            refreshlayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onSuccess(HomeResponse response) {
        refreshlayout.finishRefresh();
        if (response.data != null) {
            headLists.clear();
            String data = new Gson().toJson(response);
            SharedPreferencesUtils.saveHomeData(data);
            headLists.addAll(response.data);
            headAdapter.notifyDataSetChanged();
            getMvpPresenter().getIndexLoveData(page);
        }
    }

    @Override
    public void onLoveSuccess(GoodsMallResponse response) {
        refreshlayout.finishLoadmore();
        if (response.data != null) {
            totalPage = response.data.totalPage;
            if (page == 1) {
                goodsLists.clear();
                if (!hasAddHeadTitle) {
                    title.setText(response.data.title);
                    ImageLoaderUtils.displayImage(this, response.data.iconUrl, icon, R.drawable.defalut_img);
                    titleView.setVisibility(View.VISIBLE);
                }
            }
            if (response.data.list != null) {
                goodsLists.addAll(response.data.list);
                wrapper.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onLoading() {}

    private void initView(View view) {
        search = (LinearLayout) view.findViewById(R.id.search);
        refreshlayout = (SmartRefreshLayout) view.findViewById(R.id.refreshlayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        errorLayout = (LinearLayout) view.findViewById(R.id.error_layout);
        errorRetry = (TextView) view.findViewById(R.id.error_retry);
        top = view.findViewById(R.id.top);
        errorRetry.setOnClickListener(v -> {
            refreshlayout.autoRefresh();
            refreshlayout.setVisibility(View.VISIBLE);
            errorLayout.setVisibility(View.GONE);
        });
        search.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), HomeSearchActivity.class);
            intent.putExtra(HomeSearchActivity.SEARCH_FROM, "Home");
            startActivity(intent);
        });
        top.setOnClickListener(v -> {
            top.setVisibility(View.GONE);
            recyclerView.smoothScrollToPosition(0);
        });
        setRecyclerView();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                mCurrentY += dy;
                if (mCurrentY > 2500) {
                    top.setVisibility(View.VISIBLE);
                } else {
                    top.setVisibility(View.GONE);
                }
            }
        });
        //避免更新数据是刷新闪退
        recyclerView.setOnTouchListener((v, event) -> {
                    if (refreshlayout.isRefreshing()) {
                        return true;
                    } else {
                        return false;
                    }
                }
        );

        refreshlayout.setEnableLoadmore(true);
        refreshlayout.setOnRefreshListener(refreshlayout -> {
            refreshlayout.setLoadmoreFinished(false);
            page = 1;
            totalPage = 0;
            goodsLists.clear();
            getMvpPresenter().getIndexHeadData();
        });
        refreshlayout.setOnLoadmoreListener(refreshlayout -> {
            page = page + 1;
            if (page <= totalPage) {
                refreshlayout.setLoadmoreFinished(false);
                getMvpPresenter().getIndexLoveData(page);
            } else {
                refreshlayout.finishLoadmore();
                refreshlayout.setLoadmoreFinished(true);
            }
        });
    }

    private void setRecyclerView() {
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recyclerView.setItemAnimator(null);
        recyclerView.setItemViewCacheSize(20);
        CommonAdapter<GoodsItemsBean> adapter = new CommonAdapter<GoodsItemsBean>(getActivity(), R.layout.item_classification_mall, goodsLists) {
            @Override
            protected void convert(ViewHolder holder, GoodsItemsBean goodsItemsBean, int position) {
                Glide.with(IndexFragment.this).load(goodsItemsBean.imgUrl).into((ImageView) holder.getView(R.id.goods_img));
                ImageLoaderUtils.displayImage(IndexFragment.this, goodsItemsBean.imgUrl, holder.getView(R.id.goods_img));
                if ("43".equals(goodsItemsBean.shopId)) {
                    holder.setText(R.id.goodsfrom, "严选直供");
                    holder.setVisible(R.id.goodsfrom, true);
                } else if ("10".equals(goodsItemsBean.shopId)) {
                    holder.setText(R.id.goodsfrom, "京东直供");
                    holder.setVisible(R.id.goodsfrom, true);
                } else {
                    holder.setVisible(R.id.goodsfrom, false);
                }
                holder.setText(R.id.goods_name, goodsItemsBean.title);
                holder.setText(R.id.integral, "¥ " + goodsItemsBean.price);
                holder.itemView.setOnClickListener(v -> IndexPresenter.setOnClick(getActivity(), goodsItemsBean));
            }
        };
        wrapper = new HeaderAndFooterWrapper(adapter);
        RecyclerView headerList = new RecyclerView(getActivity());
        RecyclerView.LayoutParams params = new GridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerList.setLayoutParams(params);
        /*headerList.setLayoutManager(new FullyLinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });*/
        headerList.setLayoutManager(new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        headAdapter = new MultiItemTypeAdapter<>(getContext(), headLists);
        headAdapter.addItemViewDelegate(new BannerItemViewDelegate(getActivity()));
        headAdapter.addItemViewDelegate(new MainMenuItemViewDelegate(getActivity()));
        headAdapter.addItemViewDelegate(new CategoryItemViewDelegate(getActivity()));
        headAdapter.addItemViewDelegate(new TitleItemViewDelegate(getActivity()));
        headAdapter.addItemViewDelegate(new GoodsItemViewDelegate(getActivity()));
        headerList.setAdapter(headAdapter);
        titleView = View.inflate(getActivity(), R.layout.index_title_view, null);
        title = titleView.findViewById(R.id.title);
        icon = titleView.findViewById(R.id.icon);
        wrapper.addHeaderView(headerList);
        titleView.setVisibility(View.GONE);
        wrapper.addHeaderView(titleView);
        recyclerView.addItemDecoration(new RecyclerGriadViewItemDecoration(Utils.dip2px(getActivity(), 8), wrapper.getHeadersCount(), 0));
        recyclerView.setAdapter(wrapper);
    }
}
